package com.java.jetpackdemo.savestate

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel

class SaveStateViewModel(handle: SavedStateHandle) : ViewModel() {
    private var linkNumber: MutableLiveData<Int> = MutableLiveData()

    private var handle = handle

    //初始化数据
    init {
        linkNumber.value = 0
    }

    //将数据加1
    public fun add() {
        getNumber().value = getNumber().value?.plus(1)
    }

    //获取数据
    public fun getNumber(): MutableLiveData<Int> {
        if (!handle.contains(SaveStateActivity.KEY_NUMBER)) {
            handle.set(SaveStateActivity.KEY_NUMBER, 0)
        }
        return handle.getLiveData(SaveStateActivity.KEY_NUMBER)
    }
}